<template>
  <div class="inform-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="通知单编号">
          <el-input v-model="searchForm.informCode" placeholder="请输入通知单编号"></el-input>
        </el-form-item>
        <el-form-item label="通知单名称">
          <el-input v-model="searchForm.informName" placeholder="请输入通知单名称"></el-input>
        </el-form-item>
        <el-form-item label="采购订单编号">
          <el-input v-model="searchForm.purchaseCode" placeholder="请输入采购订单编号"></el-input>
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="searchForm.supplierName" placeholder="请输入供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="到货日期">
          <el-date-picker
            v-model="searchForm.deliveryDate"
            type="date"
            placeholder="请选择到货日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select v-model="searchForm.status" style="width: 150px;" placeholder="请选择单据状态" clearable>
            <el-option label="待入库" value="待入库"></el-option>
            <el-option label="草稿" value="草稿"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operations">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 新增
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
        <el-icon><Delete /></el-icon> 批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      v-loading="loading"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" />
      <el-table-column prop="informCode" label="通知单编号" min-width="140">
        <template #default="scope">
          <el-link type="primary" @click="handleViewDetail(scope.row)">
            {{ scope.row.informCode }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="informName" label="通知单名称" min-width="140" />
      <el-table-column prop="purchaseCode" label="采购订单编号" min-width="140" />
      <el-table-column prop="supplierName" label="供应商名称" min-width="140" />
      <el-table-column prop="linkMan" label="联系人" min-width="100" />
      <el-table-column prop="phone" label="联系方式" min-width="120" />
      <el-table-column prop="deliveryDate" label="到货日期" min-width="120">
        <template #default="scope">
          {{ formatDate(scope.row.deliveryDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="states" label="单据状态" min-width="100">
        <template #default="scope">
          <el-tag :type="scope.row.states === 1 ? 'warning' : 'info'">
            {{ scope.row.states === 1 ? '待入库' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="pagination.pageSizes"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="inform-form"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="通知单编号" prop="informCode">
              <div class="input-with-switch">
                <el-input
                  v-model="form.informCode"
                  placeholder="请输入通知单编号"
                  :disabled="form.autoGenerate"
                ></el-input>
                <el-switch
                  v-model="form.autoGenerate"
                  @change="handleAutoGenerateChange"
                  style="margin-left: 10px"
                />
                <span class="switch-label">自动生成</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="通知单名称" prop="informName">
              <el-input v-model="form.informName" placeholder="请输入通知单名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购订单编号" prop="purchaseCode">
              <el-input v-model="form.purchaseCode" placeholder="请输入采购订单编号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplierCode">
              <el-input
                v-model="form.supplierName"
                placeholder="请选择供应商"
                readonly
                @click="openSupplierSelect"
              >
                <template #append>
                  <el-button @click.stop="openSupplierSelect">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="linkMan">
              <el-input v-model="form.linkMan" placeholder="请输入联系人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系方式"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="到货日期" prop="deliveryDate">
              <el-date-picker
                v-model="form.deliveryDate"
                type="date"
                placeholder="请选择到货日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="descs">
          <el-input
            v-model="form.descs"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>

        <!-- 物料信息部分 -->
        <div class="material-info">
          <div class="sub-title">物料信息</div>
          
          <!-- 物料操作按钮 -->
          <div class="operation-bar">
            <el-button type="primary" plain @click="handleAdd">
              <el-icon><Plus /></el-icon> 新增
            </el-button>
            <el-button type="danger" plain @click="handleBatchDelete" :disabled="selectedMaterials.length === 0">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </div>

          <!-- 物料表格 -->
          <el-table
            ref="materialTableRef"
            :data="materialTableData"
            border
            style="width: 100%"
            v-loading="materialLoading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="materialCode" label="物料编码" min-width="150">
              <template #default="scope">
                <a 
                  href="javascript:;" 
                  class="material-code-link"
                  @click="handleViewDetail(scope.row)"
                >
                  {{ scope.row.materialCode }}
                </a>
              </template>
            </el-table-column>
            <el-table-column prop="materialName" label="物料名称" min-width="120" />
            <el-table-column prop="specification" label="规格型号" min-width="120" />
            <el-table-column prop="unit" label="单位" min-width="80" />
            <el-table-column prop="quantity" label="到货数量" min-width="100" />
            <el-table-column prop="isInspection" label="是否检验" min-width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isInspection ? 'success' : 'info'">
                  {{ scope.row.isInspection ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="qualifiedQuantity" label="合格数量" min-width="100" />
            <el-table-column prop="inspectionNo" label="检验单号" min-width="120" />
            <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
            <el-table-column fixed="right" label="操作" width="150" align="center">
              <template #default="scope">
                <div class="operation-buttons">
                  <el-button link type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
                  <el-button link type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSave">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 供应商选择对话框 -->
    <supplier-select
      v-model:visible="supplierSelectVisible"
      @select="handleSupplierSelect"
    />

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="查看到货通知单"
      width="1000px"
      destroy-on-close
    >
      <!-- 基本信息部分 -->
      <el-form :model="detailForm" label-width="120px" disabled>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="通知单编号">
              <el-input v-model="detailForm.informCode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="通知单名称">
              <el-input v-model="detailForm.informName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购订单编号">
              <el-input v-model="detailForm.purchaseCode" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="供应商">
              <el-input v-model="detailForm.supplierName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="到货日期">
              <el-date-picker
                v-model="detailForm.deliveryDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="联系人">
              <el-input v-model="detailForm.linkMan" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式">
              <el-input v-model="detailForm.phone" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="detailForm.descs"
                type="textarea"
                :rows="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 物料信息表格 -->
      <div class="sub-title">物料信息</div>
      <el-table
        :data="materialTableData"
        border
        style="width: 100%"
        v-loading="materialLoading"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="materialCode" label="物料编码" min-width="150" />
        <el-table-column prop="materialName" label="物料名称" min-width="120" />
        <el-table-column prop="specification" label="规格型号" min-width="120" />
        <el-table-column prop="flats" label="单位" width="80" align="center" />
        <el-table-column prop="quantity" label="到货数量" width="100" align="center" />
        <el-table-column prop="isInspection" label="是否检验" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isInspection ? 'success' : 'info'">
              {{ scope.row.isInspection ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="qualifiedQuantity" label="合格数量" width="100" align="center" />
        <el-table-column prop="inspectionNo" label="检验单号" min-width="120" />
        <el-table-column prop="descs" label="备注" min-width="120" show-overflow-tooltip />
      </el-table>

      <!-- 物料表格分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="materialPagination.currentPage"
          v-model:page-size="materialPagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="materialPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleMaterialSizeChange"
          @current-change="handleMaterialCurrentChange"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改到货通知单"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="100px"
        class="inform-form"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="通知单编号" prop="informCode">
              <el-input v-model="editForm.informCode" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="通知单名称" prop="informName">
              <el-input v-model="editForm.informName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购订单编号" prop="purchaseCode">
              <el-input v-model="editForm.purchaseCode"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplierName">
              <el-input v-model="editForm.supplierName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="linkMan">
              <el-input v-model="editForm.linkMan"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="editForm.phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="到货日期" prop="deliveryDate">
              <el-date-picker
                v-model="editForm.deliveryDate"
                type="date"
                placeholder="请选择到货日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="descs">
          <el-input
            v-model="editForm.descs"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>

        <!-- 物料信息 -->
        <div class="material-section">
          <div class="section-header">
            <div class="title">物料信息</div>
            <div class="operations">
              <el-button type="primary" @click="handleAddMaterial">
                <el-icon><Plus /></el-icon> 新增
              </el-button>
              <el-button type="danger" @click="handleBatchDeleteMaterial" :disabled="selectedMaterials.length === 0">
                <el-icon><Delete /></el-icon> 批量删除
              </el-button>
            </div>
          </div>
          
          <el-table
            :data="editMaterialTableData"
            border
            @selection-change="handleMaterialSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="materialCode" label="物料编码" min-width="120" />
            <el-table-column prop="materialName" label="物料名称" min-width="120" />
            <el-table-column prop="specification" label="规格型号" min-width="120" />
            <el-table-column prop="unit" label="单位" width="80" align="center" />
            <el-table-column prop="quantity" label="到货数量" width="100" align="center">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.quantity" 
                  :min="0" 
                  :precision="2"
                  controls-position="right"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column prop="isInspection" label="是否检验" width="100" align="center">
              <template #default="scope">
                <el-switch v-model="scope.row.isInspection" />
              </template>
            </el-table-column>
            <el-table-column prop="qualifiedQuantity" label="合格数量" width="100" align="center">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.qualifiedQuantity" 
                  :min="0" 
                  :max="scope.row.quantity"
                  :precision="2"
                  controls-position="right"
                  style="width: 100%"
                  :disabled="!scope.row.isInspection"
                />
              </template>
            </el-table-column>
            <el-table-column prop="inspectionNo" label="检验单号" min-width="120">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.inspectionNo"
                  :disabled="!scope.row.isInspection"
                  placeholder="请输入检验单号"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button type="primary" link @click="handleEditMaterial(scope.$index, scope.row)">
                  修改
                </el-button>
                <el-button type="danger" link @click="handleDeleteMaterial(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 物料选择组件 -->
    <material-select
      v-model:visible="materialSelectVisible"
      @select="handleMaterialSelect"
    />

    <!-- 物料编辑对话框 -->
    <el-dialog
      v-model="materialDialogVisible"
      :title="materialDialogTitle"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="materialFormRef"
        :model="materialForm"
        label-width="100px"
      >
        <el-form-item label="物料编码" required>
          <div class="input-with-select">
            <el-input
              v-model="materialForm.materialCode"
              placeholder="请选择物料"
              readonly
              @click="openMaterialSelect"
            >
              <template #append>
                <el-button @click.stop="openMaterialSelect">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>

        <el-form-item label="物料名称">
          <el-input v-model="materialForm.materialName" disabled></el-input>
        </el-form-item>

        <el-form-item label="规格型号">
          <el-input v-model="materialForm.specification" disabled></el-input>
        </el-form-item>

        <el-form-item label="单位">
          <el-input v-model="materialForm.unit" disabled></el-input>
        </el-form-item>

        <el-form-item label="到货数量" required>
          <el-input-number
            v-model="materialForm.quantity"
            :min="0"
            :precision="2"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="是否检验">
          <el-switch v-model="materialForm.isInspection"></el-switch>
        </el-form-item>

        <el-form-item label="合格数量" v-if="materialForm.isInspection">
          <el-input-number
            v-model="materialForm.qualifiedQuantity"
            :min="0"
            :max="materialForm.quantity"
            :precision="2"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="检验单号" v-if="materialForm.isInspection">
          <el-input
            v-model="materialForm.inspectionNo"
            placeholder="请输入检验单号"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="materialForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="materialDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveMaterial">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete, Edit } from '@element-plus/icons-vue'
import http from '@/api/http'
import SupplierSelect from './components/SupplierSelect.vue'

// 表格数据
const tableData = ref([])
// 加载状态
const loading = ref(false)
// 选中的行
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  informCode: '',
  informName: '',
  purchaseCode: '',
  supplierName: '',
  deliveryDate: '',
  status: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 15, 30, 50]
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增到货通知单')
const formRef = ref(null)
const supplierSelectVisible = ref(false)

// 表单数据
const form = reactive({
  informCode: '',
  informName: '',
  purchaseCode: '',
  supplierCode: '',
  supplierName: '',
  linkMan: '',
  phone: '',
  deliveryDate: '',
  descs: '',
  autoGenerate: true
})

// 表单验证规则
const rules = {
  informCode: [
    { required: true, message: '请输入通知单编号', trigger: 'blur' }
  ],
  informName: [
    { required: true, message: '请输入通知单名称', trigger: 'blur' }
  ],
  purchaseCode: [
    { required: true, message: '请输入采购订单编号', trigger: 'blur' }
  ],
  supplierCode: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  linkMan: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  deliveryDate: [
    { required: true, message: '请选择到货日期', trigger: 'change' }
  ]
}

// 详情对话框相关数据
const detailDialogVisible = ref(false)
const detailForm = ref({
  informCode: '',
  informName: '',
  purchaseCode: '',
  supplierName: '',
  deliveryDate: '',
  linkMan: '',
  phone: '',
  descs: ''
})
const materialTableData = ref([])
const materialLoading = ref(false)
const materialPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 编辑对话框相关
const editDialogVisible = ref(false)
const editForm = reactive({
  id: 0,
  informCode: '',
  informName: '',
  purchaseCode: '',
  supplierCode: '',
  supplierName: '',
  linkMan: '',
  phone: '',
  deliveryDate: '',
  descs: '',
  autoGenerate: false
})

// 物料表格数据
const editMaterialTableData = ref([])
const materialDialogVisible = ref(false)
const materialSelectVisible = ref(false)

// 物料表单数据
const materialForm = reactive({
  id: 0,
  materialCode: '',
  materialName: '',
  specification: '',
  unit: '',
  quantity: 0,
  isInspection: false,
  qualifiedQuantity: 0,
  inspectionNo: '',
  remark: ''
})

// 物料相关
const selectedMaterials = ref([])
const materialDialogTitle = ref('新增物料')
const editingMaterialIndex = ref(-1)

// 存储所有物料数据，用于分页
const allMaterialData = ref([])

// 获取列表数据
const getInformList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      PageIndex: pagination.currentPage , // 后端从0开始计数
      PageSize: pagination.pageSize
    }

    // 添加其他查询条件（只添加有值的条件）
    if (searchForm.informCode?.trim()) params.InformCode = searchForm.informCode.trim()
    if (searchForm.informName?.trim()) params.InformName = searchForm.informName.trim()
    if (searchForm.purchaseCode?.trim()) params.PurchaseCode = searchForm.purchaseCode.trim()
    if (searchForm.supplierName?.trim()) params.SupplierName = searchForm.supplierName.trim()
    if (searchForm.deliveryDate) params.DeliveryDate = searchForm.deliveryDate
    if (searchForm.status) params.States = searchForm.status

    console.log('发送请求参数:', params)
    const res = await http.get('/api/Inform/QueryInformList', params, true)
    console.log('API返回数据:', res)

    // 检查返回的数据结构
    if (res && res.status === true && res.data && res.data.data) {
      // 设置表格数据 - 使用嵌套的data数组
      tableData.value = res.data.data
      // 设置总条数
      pagination.total = res.data.totalCount || res.data.data.length
      
      console.log('处理后的表格数据:', tableData.value)
      console.log('总条数:', pagination.total)
      
      if (tableData.value.length === 0) {
        ElMessage.info('暂无数据')
      }
    } else {
      console.warn('API返回异常:', res)
      ElMessage.warning(res?.message || '获取数据失败')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getInformList()
}

// 重置
const handleReset = () => {
  // 重置表单
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  // 重置分页
  pagination.currentPage = 1
  pagination.pageSize = 10
  // 重新加载数据
  getInformList()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  getInformList()
}

// 页码改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getInformList()
}

// 多选变化
const handleSelectionChange = (val) => {
  selectedRows.value = val
  console.log('选中的行:', val)
}

// 打开供应商选择
const openSupplierSelect = () => {
  supplierSelectVisible.value = true
}

// 处理供应商选择
const handleSupplierSelect = (supplier) => {
  form.supplierCode = supplier.supplierCode
  form.supplierName = supplier.supplierName
  form.linkMan = supplier.firstName || ''
  form.phone = supplier.firstPhone || ''
}

// 生成编号
const generateInformCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0') // 添加随机数
  return `AN${year}${month}${day}${hours}${minutes}${seconds}${random}`
}

// 处理自动生成开关变化
const handleAutoGenerateChange = (val) => {
  if (val) {
    form.informCode = generateInformCode()
  } else {
    form.informCode = ''
  }
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增到货通知单'
  dialogVisible.value = true
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    informCode: '',
    informName: '',
    purchaseCode: '',
    supplierCode: '',
    supplierName: '',
    linkMan: '',
    phone: '',
    deliveryDate: '',
    descs: '',
    autoGenerate: true
  })
  // 如果是自动生成，立即生成编号
  if (form.autoGenerate) {
    form.informCode = generateInformCode()
  }
}

// 保存
const handleSave = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.log('表单验证失败:', fields)
      return
    }
    
    try {
      // 如果是自动生成，在保存时重新生成编号
      if (form.autoGenerate) {
        form.informCode = generateInformCode()
      }

      const params = {
        informCode: form.informCode,
        informName: form.informName,
        purchaseCode: form.purchaseCode,
        supplierCode: form.supplierCode,
        supplierName: form.supplierName,
        linkMan: form.linkMan,
        phone: form.phone,
        deliveryDate: form.deliveryDate,
        descs: form.descs,
        states: 0
      }

      console.log('保存参数:', params)
      const res = await http.post('/api/Inform/AddInform', params)
      console.log('保存返回结果:', res)
      
      if (res && res.status === true) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        getInformList()
      } else {
        ElMessage.error(res?.message || '保存失败')
      }
    } catch (error) {
      console.error('保存失败:', error)
      ElMessage.error('保存失败')
    }
  })
}

// 查看详情
const handleViewDetail = async (row) => {
  detailForm.value = { ...row }
  detailDialogVisible.value = true
  materialPagination.currentPage = 1  // 重置分页
  await loadMaterialInfo(row)
}

// 编辑
const handleEdit = async (row) => {
  console.log('开始编辑，行数据:', row)
  // 重置表单
  Object.assign(editForm, {
    id: row.id || 0,
    informCode: row.informCode || '',
    informName: row.informName || '',
    purchaseCode: row.purchaseCode || '',
    supplierCode: row.supplierCode || '',
    supplierName: row.supplierName || '',
    linkMan: row.linkMan || '',
    phone: row.phone || '',
    deliveryDate: row.deliveryDate || '',
    descs: row.descs || '',
    autoGenerate: false
  })
  
  editDialogVisible.value = true
  materialPagination.currentPage = 1  // 重置分页
  await loadMaterialInfo(row)
}

// 加载物料信息的公共方法
const loadMaterialInfo = async (row) => {
  materialLoading.value = true
  try {
    // 构建查询参数，添加通知单编号
    const queryParams = new URLSearchParams()
    queryParams.append('pageIndex', '1')
    queryParams.append('pageSize', '999') // 获取所有数据，前端分页
    queryParams.append('informCode', row.informCode || '') // 添加通知单编号参数
    
    const response = await http.get(`/api/MaterialProduct/GetMaterialProduct?${queryParams.toString()}`)
    console.log('物料信息API返回:', response)
    
    if (response.status === true && response.data?.products) {
      // 保存所有数据
      allMaterialData.value = response.data.products.map(item => ({
        materialCode: item.materialCode || '',
        materialName: item.materialName || '',
        specification: item.specification || '',
        unit: item.unit || '',
        quantity: item.quantity || 0,
        isInspection: item.isInspection === '1',
        qualifiedQuantity: item.qualifiedQuantity || 0,
        inspectionNo: item.inspectionNo || '',
        remark: item.remark || ''
      }))
      
      // 更新总数和分页数据
      materialPagination.total = allMaterialData.value.length
      updateMaterialTableData(allMaterialData.value)
      
      console.log('处理后的物料表格数据:', materialTableData.value)
    } else {
      materialTableData.value = []
      allMaterialData.value = []
      materialPagination.total = 0
      console.warn('物料信息API返回为空')
    }
  } catch (error) {
    console.error('获取物料信息失败:', error)
    ElMessage.error('获取物料信息失败')
    materialTableData.value = []
    allMaterialData.value = []
    materialPagination.total = 0
  } finally {
    materialLoading.value = false
  }
}

// 更新物料表格数据（处理分页）
const updateMaterialTableData = (allData) => {
  const start = (materialPagination.currentPage - 1) * materialPagination.pageSize
  const end = start + materialPagination.pageSize
  materialTableData.value = allData.slice(start, end)
}

// 物料表格分页改变
const handleMaterialSizeChange = (val) => {
  materialPagination.pageSize = val
  updateMaterialTableData(allMaterialData.value)
}

const handleMaterialCurrentChange = (val) => {
  materialPagination.currentPage = val
  updateMaterialTableData(allMaterialData.value)
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该记录吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // 构建URL参数
      const params = new URLSearchParams()
      params.append('ids', row.id)
      
      const res = await http.get(`/api/Inform/DeleteInforms?${params.toString()}`, {}, true)
      console.log('删除返回结果:', res)
      
      if (res && res.status === true) {
        ElMessage.success('删除成功')
        // 刷新列表
        getInformList()
      } else {
        ElMessage.error(res?.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // 构建URL参数
      const params = new URLSearchParams()
      selectedRows.value.forEach(row => {
        params.append('ids', row.id)
      })
      
      console.log('删除参数:', params.toString())
      const res = await http.get(`/api/Inform/DeleteInforms?${params.toString()}`, {}, true)
      console.log('批量删除返回结果:', res)
      
      if (res && res.status === true) {
        ElMessage.success('删除成功')
        // 清空选中
        selectedRows.value = []
        // 刷新列表
        getInformList()
      } else {
        ElMessage.error(res?.message || '删除失败')
      }
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  try {
    const dateObj = new Date(date)
    return dateObj.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (e) {
    return date
  }
}

// 打开物料选择对话框
const openMaterialSelect = () => {
  materialSelectVisible.value = true
}

// 处理物料选择
const handleMaterialSelect = (material) => {
  console.log('选择的物料:', material)
  Object.assign(materialForm, {
    id: material.id || 0,
    materialCode: material.materialCode || '',
    materialName: material.materialName || '',
    specification: material.specification || '',
    unit: material.flats || '',  // 使用flats作为单位
    quantity: 0,
    isInspection: false,
    qualifiedQuantity: 0,
    inspectionNo: '',
    remark: material.descs || ''  // 使用descs作为备注
  })
  materialSelectVisible.value = false
}

// 新增物料
const handleAddMaterial = () => {
  materialDialogTitle.value = '新增物料'
  editingMaterialIndex.value = -1
  // 重置物料表单
  Object.assign(materialForm, {
    id: 0,
    materialCode: '',
    materialName: '',
    specification: '',
    unit: '',
    quantity: 0,
    isInspection: false,
    qualifiedQuantity: 0,
    inspectionNo: '',
    remark: ''
  })
  materialDialogVisible.value = true
}

// 物料选择变化
const handleMaterialSelectionChange = (val) => {
  selectedMaterials.value = val
}

// 编辑物料
const handleEditMaterial = (index, row) => {
  materialDialogTitle.value = '修改物料'
  editingMaterialIndex.value = index
  Object.assign(materialForm, {
    id: row.id || 0,
    materialCode: row.materialCode,
    materialName: row.materialName,
    specification: row.specification,
    unit: row.unit,
    quantity: row.quantity,
    isInspection: row.isInspection,
    qualifiedQuantity: row.qualifiedQuantity || 0,
    inspectionNo: row.inspectionNo || '',
    remark: row.remark || ''
  })
  materialDialogVisible.value = true
}

// 批量删除物料
const handleBatchDeleteMaterial = () => {
  if (selectedMaterials.value.length === 0) {
    ElMessage.warning('请选择要删除的物料')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedMaterials.value.length} 条记录吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const selectedIds = selectedMaterials.value.map(item => item.materialCode)
    editMaterialTableData.value = editMaterialTableData.value.filter(
      item => !selectedIds.includes(item.materialCode)
    )
    selectedMaterials.value = []
    ElMessage.success('删除成功')
  })
}

// 保存物料
const handleSaveMaterial = async () => {
  if (!materialFormRef.value) return
  
  try {
    const materialData = {
      id: materialForm.id,
      materialCode: materialForm.materialCode,
      materialName: materialForm.materialName,
      specification: materialForm.specification,
      unit: materialForm.unit,
      quantity: materialForm.quantity,
      isInspection: materialForm.isInspection,
      qualifiedQuantity: materialForm.qualifiedQuantity,
      inspectionNo: materialForm.inspectionNo,
      remark: materialForm.remark
    }

    // TODO: 调用保存API
    console.log('保存物料数据:', materialData)
    
    materialDialogVisible.value = false
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 删除物料
const handleDeleteMaterial = (index) => {
  editMaterialTableData.value.splice(index, 1)
}

// 保存修改
const handleSaveEdit = async () => {
  try {
    if (!editForm.informCode) {
      ElMessage.warning('通知单编号不能为空')
      return
    }

    // 构建提交的参数
    const params = {
      id: editForm.id || 0,
      informCode: editForm.informCode,
      informName: editForm.informName,
      purchaseCode: editForm.purchaseCode,
      supplierCode: editForm.supplierCode,
      supplierName: editForm.supplierName,
      linkMan: editForm.linkMan,
      phone: editForm.phone,
      deliveryDate: editForm.deliveryDate,
      descs: editForm.descs,
      inboundListCode: editForm.inboundListCode || '',
      materials: editMaterialTableData.value.map(item => ({
        id: item.id || 0,
        materialCode: item.materialCode,
        materialName: item.materialName,
        specification: item.specification,
        unit: item.unit,
        quantity: item.quantity,
        isInspection: item.isInspection,
        qualifiedQuantity: item.qualifiedQuantity || 0,
        inspectionNo: item.inspectionNo || '',
        remark: item.remark || ''
      }))
    }
    
    console.log('提交的修改数据:', params)
    const response = await http.post('/api/Inform/UpdateInform', params)
    if (response && response.status === true) {
      ElMessage.success('保存成功')
      editDialogVisible.value = false
      getInformList()
    } else {
      ElMessage.error(response?.message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 页面加载时获取数据
onMounted(() => {
  console.log('页面加载，开始获取数据')
  getInformList()
})

// 获取分类名称
const getCategoryName = (id) => {
  if (!id) return '-'
  const findCategoryName = (list) => {
    for (const item of list) {
      if (item.id === id) {
        return item.label
      }
      if (item.children && item.children.length) {
        const name = findCategoryName(item.children)
        if (name) return name
      }
    }
    return null
  }
  const name = findCategoryName(categoryList.value)
  return name || '-'
}

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const res = await http.get('/api/MaterialCatalog/GetMaterialCatalog')
    if (res.data) {
      categoryList.value = res.data
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    categoryList.value = []
  }
}

// 初始化数据
const initData = async () => {
  await Promise.all([fetchCategoryList(), getInformList()])
}
</script>

<style scoped>
.inform-container {
  padding: 20px;
}

.search-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.inform-form {
  padding: 20px;
}

.inform-form .el-form-item {
  margin-bottom: 20px;
}

.input-with-switch {
  display: flex;
  align-items: center;
}

.switch-label {
  margin-left: 5px;
  font-size: 14px;
  color: #606266;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}

:deep(.el-input-group__append) {
  padding: 0;
}

:deep(.el-input-group__append button) {
  margin: 0;
  border: none;
  height: 100%;
  border-radius: 0;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}

.el-button + .el-button {
  margin-left: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.sub-title {
  font-size: 16px;
  font-weight: 500;
  margin: 16px 0;
  padding-left: 8px;
  border-left: 4px solid #409eff;
}

/* 禁用状态下的输入框样式优化 */
:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-textarea.is-disabled .el-textarea__inner) {
  background-color: #f5f7fa;
}

:deep(.el-form-item.is-required:not(.is-no-asterisk)) {
  margin-bottom: 18px;
}

.material-section {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.title {
  font-size: 16px;
  font-weight: 500;
}

.operations {
  display: flex;
  gap: 10px;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-right: 30px;
}

:deep(.el-switch) {
  --el-switch-on-color: #409eff;
}

.material-info {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.operation-bar {
  margin-bottom: 15px;
}

.material-code-link {
  color: #409EFF;
  text-decoration: none;
}

.material-code-link:hover {
  text-decoration: underline;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}
</style>

